# This application is released under the GNU General Public License 
# v3 (or, at your option, any later version). You can find the full 
# text of the license under http://www.gnu.org/licenses/gpl.txt. 
# By using, editing and/or distributing this software you agree to 
# the terms and conditions of this license. 
# Thank you for using free software!

# Sensors Module (c) Whise (Helder Fraga) 2008 <helder.fraga@hotmail.com>

import screenlets
import sys
import re
import gobject
import gettext
from datetime import datetime
import commands
import time
import os
import subprocess
import gtk
# translation stuff
gettext.textdomain('screenlets')
gettext.bindtextdomain('screenlets', screenlets.INSTALL_PREFIX +  '/share/locale')

def _(s):
	return gettext.gettext(s)


# ------------------------------------------------------------------------------
# FUNCTIONS
# ------------------------------------------------------------------------------

###########################################
#                                         #
#     BANDOINE CUSTOM FUNCTION            #
#                                         #
###########################################

def get_gnome_version():
	"""Returns gnome version"""
	res = commands.getoutput('gnome-about --version')
	return res.split(" ")[2]

def get_who():
	"""return an array with an array of connection part of who"""
	res = commands.getoutput('who | awk \'{print $1"##"$2"##"$3"##"$4"##"$5}\'')
	res = res.split('\n')
	result=[]
	for item in res:
		result.append(item.split('##'))	
	return result

def get_net_ip():
	"""Returns distant ip addr"""
	from urllib2 import urlopen
	try:
		ip = urlopen("http://bandoine.hd.free.fr/what_is_my_ip.php").read()
	except:	
		try:		
			ip =  urlopen("http://www.whatismyip.com/automation/n09230945.asp").read()
		except:
			return "IP detection failed"	
	return ip

def get_lan_ip(): # by Bandoine
	"""Returns ips in a list of tuples"""
	ifconfig = commands.getoutput("ifconfig | grep Link").split("\n")
	liste_int=[]		
	for item in ifconfig:
		liste_int.append(item.split()[0])
	liste_ip=[]
	for item in liste_int:	
		if item != "lo":
			command = "ifconfig "+ item + " | grep inet\ "
			ipc = commands.getoutput(command)
			ipc = ipc.split(":") 	
			try:	
				tup = item,ipc[1].split(" ")[0]
				liste_ip.append(tup)
			except:
				tup = "failed"
	return liste_ip
	
def get_open_ports():
	"""Returns open ports in list of tuple (port/ip_protocol,state,service)"""
	#Need nmap installed	
	nmap = commands.getoutput('nmap 127.0.0.1 | grep /tcp')
	nmap = nmap.split('\n')
	nmap_splited = []
	for item in nmap:
		nmap_splited.append(item.split(' '))
	open_ports=[]
	for it in nmap_splited:
		tup = []
		for item in it:
			if item!= '':
				tup.append(item)
		open_ports.append(tup)
	return open_ports

def get_tcp_connexions():
	 """Returns tcp connexion in list of tuple (Recv-Q/Send-Q/Adresse locale/Adresse distante/Etat/(PID/Program_name))"""
	 netstat = commands.getoutput('netstat -t -p')
	 netstat = netstat.split('\n')
	 netstat_splited = []
	 for item in netstat:
	 	netstat_splited.append(item.split(' '))
	 connexions = []
	 for it in netstat_splited:
	 	if it[0] == 'tcp':
	 		tup = []
	 		for item in it:
	 			if item != '' and item != 'tcp':
	 				tup.append(item)
	 		connexions.append(tup)
	 return connexions
# TEST:
if __name__ == '__main__':
	
	# some tests
	#print get_lan_ip()
	#print get_net_ip()
	#print get_who()
	#print get_gnome_version()
	#print get_open_ports()
	print get_tcp_connexions()
